package com.quest.space.poker.biz.impl;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.quest.space.poker.base.utils.SnowFlake;
import com.quest.space.poker.dto.PlayerDto;
import com.quest.space.poker.dto.TableDto;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class TableServiceImpl{
    private static Cache<String, TableDto> tableCache = CacheBuilder.newBuilder()
            // 设置缓存的过期时间为1小时
            .expireAfterWrite(1000, TimeUnit.DAYS)
            // 设置缓存的最大容量
            .maximumSize(1000000)
            .build();


    public static List<TableDto> listInWait() {
        ConcurrentMap<String, TableDto> map = tableCache.asMap();
        if (map == null || map.isEmpty()) {
            return new ArrayList<>();
        }
        return map.values().stream().filter(t -> t.getPlayerNum() != 3).collect(Collectors.toList());
    }

    public static TableDto getTable(String tableId) {
        return tableCache.getIfPresent(tableId);
    }

    public static TableDto createTable(PlayerDto player) {
        TableDto tableDto = new TableDto();
        String id = SnowFlake.nextId();
        tableDto.setTableId(id);
        tableDto.setTableName(player.getName() + "'s game");
        List<PlayerDto> list = new ArrayList<>();
        list.add(player);
        tableDto.setPlayers(list);
        tableDto.setPlayerNum(1);
        tableCache.put(id, tableDto);
        return tableDto;
    }

    public TableDto joinTable(PlayerDto player, String tableId) {
        return tableCache.getIfPresent(tableId);
    }

    public static void putTable(TableDto table) {
        tableCache.put(table.getTableId(), table);
    }
}
